<template>
  <div class="add_container">
    添加丢失找寻
    <div class="content_box">
      <div class="img_box">
        <el-upload class="avatar-uploader"
                   action="http://localhost:9091/pet/uploadImg"
                   :show-file-list="false"
                   :data="{'petId':petForm.petId}"
                   :auto-upload="false"
                   ref="upload"
                   :on-change="imgPreview"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl"
               :src="imageUrl"
               class="avatar">
          <img v-if="imageUrl1"
               :src="imageUrl1"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div class="info_box">
        <el-form label-width="85px"
                 :rules="petRulesFrom"
                 ref="petRulesFromRef"
                 :model="petForm"
                 size="small">
          <el-form-item prop="petName"
                        label="标题:">
            <el-input v-model="petForm.petName"
                      placeholder="请填写标题"></el-input>
          </el-form-item>
          <el-form-item prop="petTypeName"
                        label="丢失位置:">
            <el-input v-model="petForm.petTypeName"
                      placeholder="填写丢失的大概地点"></el-input>
          </el-form-item>
          <el-form-item prop="petSex"
                        label="性别:">
            <el-radio-group v-model="petForm.petSex">
              <el-radio :label="1">雄</el-radio>
              <el-radio :label="2">雌</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="addr"
                        label="地址:">
            <el-input v-model="petForm.addr"></el-input>
          </el-form-item>
          <el-form-item prop="contactName"
                        label="联系人:">
            <el-input v-model="petForm.contactName"></el-input>
          </el-form-item>
          <el-form-item prop="phoneNumber"
                        label="手机:">
            <el-input v-model="petForm.phoneNumber"></el-input>
          </el-form-item>
          <el-form-item label="详情:">
            <el-input v-model="petForm.detail"
                      type="textarea"
                      :rows="3"
                      class="detail"
                      placeholder="请输入详情，包括丢失时间，衣着，宠物显著特征等">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="btn_publish"
                       @click="publish()"
                       type="success">立即发布</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>

  </div>
</template>
<script>
// import addInfo from '../../api/http.js'
import { addPetInfo } from '../../api/http'
export default {
  data () {
    const isNum = (rule, value, callback) => {
      const id = /^[0-9]*$/
      if (!id.test(value)) {
        callback(new Error('手机号只能为数字'))
      } else {
        callback()
      }
    }
    return {
      imageUrl1: '',
      imageUrl: '',
      // 宠物表单
      petForm: {
        petId: '',
        petName: '',
        petTypeName: '',
        cateGoryId: 1004,
        addr: '',
        detail: '',
        userId: 1001,
        contactName: '',
        petSex: 1,
        phoneNumber: ''
      },
      updateImgForm: {
        petId: '',
        petImg: ''
      },
      // 宠物表单校验
      petRulesFrom: {
        // 校验密码
        petName: [
          { required: true, message: '标题为必填项', trigger: 'blur' },//必填项验证
        ],
        //   校验地址
        addr: [
          { required: true, message: '品种为必填项', trigger: 'blur' },//必填项验证
        ],
        // 校验手机号
        phoneNumber: [
          { required: true, message: '手机号为必填项', trigger: 'blur' },//必填项验证
          { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' },//长度验证
          { validator: isNum, trigger: 'blur' }
        ],
      }
    }
  },
  methods: {
    // 选中上传的图片预览
    imgPreview (file, fileList) {
      let fileName = file.name;
      let regex = /(.jpg|.jpeg|.gif|.png|.bmp)$/;
      if (regex.test(fileName.toLowerCase())) {
        var url = null;
        // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
        if (window.createObjectURL != undefined) {   // basic
          url = createObjectURL(file);
        } else if (window.URL != undefined) {        // mozilla(firefox)
          url = URL.createObjectURL(file.raw);
        } else if (window.webkitURL != undefined) {  // webkit or chrome
          url = webkitURL.createObjectURL(file);
        }
        this.imageUrl1 = url

      } else {
        this.$message.error('请选择图片文件');
      }
    },
    // 返回上传的图片地址
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.updateImgForm.petId = this.petForm.petId
      this.updateImgForm.petImg = res.data.imgPath
      this.updateImg()
    },
    async updateImg () {
      const { data: res } = await this.$http.put('/pet/updateImgByPetId', this.updateImgForm)
      console.log(res.data)
    },
    // 上传 之前进行图片校验
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //  发布信息
    async publish () {
      this.petForm.userId = window.sessionStorage.getItem("userId")
      const { data: res } = await addPetInfo(this.petForm)
      console.log(res)
      if (res.code == 200) {
        this.petForm.petId = res.data.petId;
        console.log("petId:" + this.petForm.petId)
        this.$refs.upload.submit();
        this.$router.push({ path: "/lostFind" });
        return;
      }
      console.log(res.data)
    }
  },

}
</script>
<style lang="less" scoped>
.add_container {
  width: 100%;
  height: 100%;
  .content_box {
    display: flex;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 95%;
    height: 70%;
    .img_box {
      width: 50%;
      height: 100%;
      // background-color: red;

      .avatar-uploader {
        position: relative;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        background-color: rgba(197, 238, 130, 0.342);
        width: 80%;
        height: 65%;
        border: 1px dashed rgb(126, 121, 121);
        .avatar-uploader-icon {
          position: absolute;
          font-size: 50px;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
          //  background-color: darkcyan;
          color: #8c939d;
          text-align: center;
        }
        .avatar {
          position: absolute;
          font-size: 50px;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);
        }
      }
    }

    .info_box {
      width: 50%;
      height: 100%;
      // background-color: cyan;
      .el-form {
        padding-top: 0;
        padding-left: 0px;
        height: 50%;
        width: 30%;
        position: absolute;
        top: 30%;
        transform: translate(0, -50%);
        bottom: 0%;
        box-sizing: border-box;
        .btn_publish {
          width: 100%;
        }
      }
    }
    .detial {
      width: 30%;
      height: 100%;
      // background-color: blueviolet;
      .detail {
        position: relative;
        top: 50%;
        left: 0;
        transform: translate(0, -52%);
        padding: 30px;
        bottom: 0%;
        box-sizing: border-box;
      }
    }
  }
}
</style>